package com.example.socket.client;

import com.example.socket.codec.MessageCodecFactory;
import com.example.socket.handler.NettyHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;

import java.util.Map;
import java.util.Map.Entry;

/**
 * CHANNEL 初始化
 */
public class ClientHandlerInitializer extends ChannelInitializer<SocketChannel> {

    private NettyHandler handler;
    private Map<String, ChannelHandler> filters;

    private MessageCodecFactory codecFactory = new MessageCodecFactory();

    public ClientHandlerInitializer(NettyHandler handler, Map<String, ChannelHandler> filters) {
        this.handler = handler;
        this.filters = filters;
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 过滤器
        if (filters != null) {
            for (Entry<String, ChannelHandler> e : filters.entrySet()) {
                String key = e.getKey();
                ChannelHandler value = e.getValue();
                pipeline.addLast(key, value);
            }
        }
        // 编码解码器
        pipeline.addLast("CLIENT-DECODER", codecFactory.getDecoder(Integer.MAX_VALUE));
        pipeline.addLast("CLIENT-ENCODER", codecFactory.getEncoder());

        // 处理器
        pipeline.addLast("CLIENT-HANDLER", handler);
    }
}
